import React from 'react';
import { Drawer, Badge, Button, List, message, notification, Spin, Tooltip } from 'antd';
import './style.scss';
import {
  DownloadOutlined,
  FileExcelOutlined,
  DeleteOutlined,
  RightOutlined,
} from '@ant-design/icons';
import InfiniteScroll from 'react-infinite-scroller';
import { JSONObject } from 'admin/schema/common';
import { DownloadTaskListInfo } from 'admin/schema/DownloadTask';
import { getSocket } from 'servers/socket';
import { CallRecordDownloadMsg } from 'admin/schema/SocketMessage';

import {
  getDownloadFocusCount,
  modifyDownloadTask,
  deleteDownloadTask,
  getDownloadTaskList,
} from 'admin/servers/servers';

interface IProp {
  fn: any; // 暴露父级方法
  visible: boolean; // 抽屉显示隐藏
}

interface IState {
  current: number;
  pageSize: number;
  newsCount: number;
  count: number;
  loading: boolean;
  hasMore: boolean;
  datalist: DownloadTaskListInfo[];
}

class DownloadModel extends React.Component<IProp, IState> {
  constructor(prop: IProp) {
    super(prop);
    this.state = {
      current: 1,
      pageSize: 10,
      newsCount: 0,
      count: 0,
      loading: false,
      hasMore: false,
      datalist: [],
    };
  }
  componentDidMount() {
    this.addSocketEvent();
    this.loadNewsCount();
  }

  componentWillUnmount = () => {
    this.removeSocketEvent();
    this.setState = (state, callback) => {
      return;
    };
  };

  /**
   * 加载列表数据
   */
  private loadMoreData() {
    const { datalist, current, pageSize, count } = this.state;
    if (count === 0) {
      // 场景：1.初始化；2.没有下载任务；
      this.setState({
        loading: false,
        hasMore: false,
        datalist: [],
        current: 1,
      });
    }
    if (count > 0 && datalist?.length >= count) {
      // 场景：有下载任务--已全部显示到列表中
      message.info('全部加载完成');
      console.log('全部加载完成');
      this.setState({
        loading: false,
        hasMore: false,
      });
      return;
    }
    // 场景：有下载任务--部分显示到列表中--继续请求
    this.setState({
      loading: true,
      hasMore: true,
    });
    getDownloadTaskList({
      pageNo: current,
      pageSize: pageSize,
    })
      .then(res => {
        this.setState({
          loading: false,
        });
        if (res.code === 0) {
          if (!res.count) {
            // 场景：下载任务数量为0
            return;
          }
          this.setState({
            current: current + 1,
            count: res.count || 0,
            datalist: datalist.concat(res.data), //拼接每次加载的数据
          });
        }
      })
      .catch(error => {
        console.error(`系统异常: ${JSON.stringify(error)}`);
        this.setState({
          loading: false,
        });
      });
  }
  /**
   * 取消新任务红点标识
   */
  private handleFocus(taskId: number) {
    modifyDownloadTask(taskId).then(res => {
      if (res.code === 0) {
        const { datalist } = this.state;
        datalist.forEach((obj: any) => {
          if (obj.downloadTaskId === taskId) {
            obj.isNew = 0;
          }
        });
        this.setState({
          datalist: [...datalist],
        });
        this.loadNewsCount();
      } else {
        message.error(`${res.tips}(错误码: ${res.code})`);
      }
    });
  }
  /**
   * 删除全部下载任务
   */
  private deleteAllTask() {
    deleteDownloadTask()
      .then(res => {
        if (res.code === 0) {
          message.success('删除成功');
          this.setState({
            count: 0,
            current: 1,
          });
          this.loadMoreData();
          this.loadNewsCount();
        }
      })
      .catch(error => {
        console.error(`系统异常: ${JSON.stringify(error)}`);
      });
  }
  /**
   * 打开抽屉
   */
  public openDownloadDrawer() {
    this.props.fn('download');
    setTimeout(() => {
      this.loadMoreData();
    }, 100);
  }
  /**
   * 关闭抽屉
   */
  public closeDownloadDrawer() {
    this.props.fn();
    this.setState({
      current: 1,
      datalist: [],
    });
  }
  /**
   * 获取最新下载任务总数
   */
  private loadNewsCount() {
    // getDownloadFocusCount()
    //   .then(res => {
    //     if (res.code === 0) {
    //       this.setState({
    //         newsCount: res.count || 0,
    //       });
    //     }
    //   })
    //   .catch(error => {
    //     console.error(`系统异常: ${JSON.stringify(error)}`);
    //   });
  }

  /**下载通知弹窗-文件准备好，可以下载 */
  private downloadNotice(fileUrl: string, taskId: number) {
    const key = 'notice_' + taskId + `_${Date.now()}`;
    const btn = (
      <Button
        type="link"
        size="small"
        href={fileUrl}
        onClick={() => {
          notification.close(key);
        }}
      >
        下载
      </Button>
    );
    // 关闭
    const close = () => {
      console.log('下载通知弹窗-关闭', key);
    };
    // 打开【下载管理】抽屉
    const handleClick = () => {
      notification.close(key);
      if (!this.props.visible) {
        this.openDownloadDrawer();
        setTimeout(() => {
          this.handleFocus(taskId);
        }, 100);
      }
    };
    notification.open({
      message: '温馨提示：',
      description: '数据已准备好，请',
      icon: <FileExcelOutlined style={{ fontSize: 28, color: '#3b9162' }} />,
      top: 55,
      btn,
      key,
      onClose: close,
      className: 'custom-download-notification',
      duration: 5,
      style: {
        width: 280,
      },
      onClick: handleClick,
    });
  }

  private addSocketEvent(): void {
    console.log('下载消息推送事件-事件-start');
    getSocket().addEvent('callRecordDownloadCompleteEvent', (data: JSONObject) => {
      // 接收到消息,文件准备好
      console.log(data, '下载消息推送----');
      data = data as CallRecordDownloadMsg;
      const { fileUrl, downloadTaskId } = data;
      // 下载中心总数-更新
      this.loadNewsCount();
      if (this.props.visible) {
        // 弹窗开启时：列表数据-更新
        this.setState(
          {
            current: 1,
            datalist: [],
          },
          () => {
            this.loadMoreData();
          }
        );
      }
      this.downloadNotice((process.env.REACT_APP_API_URL || '') + fileUrl, downloadTaskId);
    });
  }

  /** 卸载socket事件*/
  private removeSocketEvent() {
    console.log('下载消息推送事件->>>>socket事件-删除');
    const socket = getSocket();
    socket.removeEvent(['callRecordDownloadCompleteEvent']);
  }
  render() {
    const { newsCount, loading, hasMore, datalist, count } = this.state;
    return (
      <div className="layout-header-download">
        <Badge size="small" count={newsCount} title="新消息">
          <Button
            className="download-btn"
            type="primary"
            // shape="round"
            // icon={<DownloadOutlined />}
            onClick={() => {
              if (this.props.visible) {
                this.closeDownloadDrawer();
              } else {
                this.openDownloadDrawer();
              }
            }}
          >
            下载管理
          </Button>
        </Badge>
        {this.props.visible && (
          <div className="download-wrapper">
            <Drawer
              className="download-drawer"
              title="下载管理"
              placement="right"
              width={400}
              closable={true}
              closeIcon={<RightOutlined style={{ color: '#1890ff' }} />}
              mask={true}
              onClose={() => {
                this.closeDownloadDrawer();
              }}
              visible={this.props.visible}
              footer={false}
              getContainer={false}
              style={{ position: 'absolute' }}
            >
              <Tooltip placement="bottomRight" title={count ? '删除全部' : ''}>
                <Button
                  disabled={!count}
                  className="delete-all-btn"
                  type="link"
                  onClick={() => {
                    this.deleteAllTask();
                  }}
                >
                  <DeleteOutlined style={{ fontSize: 20 }} />
                </Button>
              </Tooltip>
              {/* 滚动加载列表 */}
              <div
                className="demo-infinite-container"
                style={{
                  height: 'calc(100% - 5px)',
                  overflow: 'auto',
                }}
              >
                <InfiniteScroll
                  initialLoad={false}
                  pageStart={0}
                  loadMore={() => {
                    this.loadMoreData();
                  }}
                  threshold={1}
                  hasMore={!loading && hasMore}
                  useWindow={false} //****将滚动侦听器添加到窗口，或者添加组件的parentNode****
                >
                  {/* !loading &&  */}
                  {
                    <List
                      dataSource={datalist}
                      renderItem={(item: any) => (
                        <List.Item
                          onMouseEnter={() => {
                            if (!item.isNew) {
                              // 非新任务
                              return false;
                            }
                            this.handleFocus(item.downloadTaskId);
                          }}
                          key={item.downloadTaskId}
                          actions={[
                            (item.taskStatus === 2 && (
                              <Button
                                type="link"
                                size="small"
                                href={(process.env.REACT_APP_API_URL || '') + item.fileUrl} // 前面拼接api接口路径
                                onClick={() => {
                                  if (!item.isNew) {
                                    // 非新任务
                                    return false;
                                  }
                                  this.handleFocus(item.downloadTaskId);
                                }}
                              >
                                下载
                              </Button>
                            )) ||
                              (item.taskStatus <= 1 && <span>准备中</span>) ||
                              (item.taskStatus > 2 && <span>失败</span>),
                          ]}
                        >
                          <List.Item.Meta
                            className="list-item-meta"
                            avatar={
                              <div>
                                <Badge dot={item.isNew ? true : false}>
                                  <FileExcelOutlined style={{ fontSize: 32, color: '#3b9162' }} />
                                </Badge>
                              </div>
                            }
                            title={
                              <span>
                                {/* 文件名{item.downloadTaskId} */}
                                {/* 上面的id调试用 */}
                                文件名:{item.fileName}
                              </span>
                            }
                            description={<span>导出时间:{item.exportTime}</span>}
                          />
                        </List.Item>
                      )}
                    />
                  }
                  <Spin spinning={loading && hasMore} size="large"></Spin>
                </InfiniteScroll>
                {loading && hasMore && <div className="loading-txt">加载中</div>}
                {count > 0 && !loading && !hasMore && <div className="footer-txt">已无更多</div>}
              </div>
            </Drawer>
          </div>
        )}
      </div>
    );
  }
}
export default DownloadModel;
